var interval;
var app = getApp()
import utils from '../../utils/util'
import {
  request,
  setConfig
} from '../../utils/promise-request.js';
import {
  post
} from '../../utils/promise-request.js';
// 根据自身需求，来定制 request
setConfig({
  request: wx.uploadFile, // 使用 wx.uploadFile 提供的请求方法
  Promise,
  concurrency: 5, // 限制最大并发数为 5
})
Page({
  data: {
    currentcourse: null,
    score: "获取位置中...",
    course: null,
    time: null
  },

  onLoad(options) {
    var that = this;
    getTodayCourse(that, app.globalData.sId);
    console.log(options);
    console.log("1")
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      success: function (res) {
        console.log("2")
        var latitude = res.latitude;
        var longitude = res.longitude;
        console.log(options.latitude + ',' + options.longitude);
        wx.request({
          url: `https://restapi.amap.com/v3/distance?key=471dde3ac0c195c0004cec6d1394e915`,
          data: {
            origins: `${latitude},${longitude}`,
            destination: `${options.latitude},${options.longitude}`,
            type: 0,
          },
          success(res) {
            console.log("3")
            console.log(res.data);
            if (res.data.results[0].distance > 100) {
              wx.redirectTo({
                url: "../end/end?state=0&course=" + that.data.course + "&cTime=" + that.data.time
              })
            } else {
              that.setData({
                score: "正在识别请稍后..."
              })
              var face_token
              that.ctx = wx.createCameraContext();
              console.log("4")
              //获取face_token
              wx.request({
                url: `https://geek-team.xin/student/findById?sId=${app.globalData.sId}`,
                success(e) {
                  console.log("5")
                  console.log(e.data.sData)
                  face_token = e.data.sData
                  //定时器,1秒
                  console.log("6")
                  interval = setInterval(
                    function () {
                      console.log("7")
                      recognise(that, face_token, options);
                    }, 1000);
                },
                fail: (e) => console.log(e)
              })
            }
          }
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(interval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(interval);
  },

  back() {
    // 往上一级页面传参
    var pages = getCurrentPages();
    // var currPage = pages[pages.length - 1]; // 当前页面
    var prevPage = pages[pages.length - 2]; // 上一级页面
    prevPage.setData({
      faceToken: null,
    })
  },

})
/**
 * 识别
 * @param {*} that 
 */
function recognise(that, face_token, options) {
  //拍照
  that.ctx.takePhoto({
    quality: 'normal',
    success: (res) => {
      that.setData({
        src: res.tempImagePath,
        // mask:''
      })
    }
  })
  console.log("8")
  //先检测后识别
  if (that.data.src) {
    request({
        url: 'https://api-cn.faceplusplus.com/facepp/v3/detect',
        filePath: that.data.src,
        name: 'image_file',
        formData: {
          api_key: 'e7mQCRQH_yCEDxmMsVB-wKwCBMDrnEr-',
          api_secret: 'n5gRQq_T_nMghOgF9QW9hp8WLHmUna-h',
          return_landmark: '2',
          return_attributes: "gender,age,smiling,emotion,beauty"
        }
      })
      .then(res => {
        var _data = JSON.parse(res.data);
        console.log(_data)
        console.log("9")
        if (_data != {
            error_message: "CONCURRENCY_LIMIT_EXCEEDED"
          } && _data.faces.length != 0) {
          var face = _data.faces[0]
          console.log(`face_token:${face.face_token}`)
          wx.request({
            method: 'POST',
            url: 'https://api-cn.faceplusplus.com/facepp/v3/compare',
            data: {
              api_key: 'e7mQCRQH_yCEDxmMsVB-wKwCBMDrnEr-',
              api_secret: 'n5gRQq_T_nMghOgF9QW9hp8WLHmUna-h',
              face_token1: _data.faces[0].face_token,
              face_token2: face_token
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success(res1) {
              console.log("10")
              console.log(res1)
              if (res1.statusCode == 403) {
                console.log(`充钱吧:${res1.data.error_message}`)
              } else if (res1.statusCode == 200) {
                console.log(res1.data);
                that.setData({
                  score: "置信度" + res1.data.confidence
                })
                // 一组用于参考的置信度阈值，包含以下三个字段。每个字段的值为一个 [0,100] 的浮点数，小数点后 3 位有效数字。
                //1e-3：误识率为千分之一的置信度阈值；
                //1e-4：误识率为万分之一的置信度阈值；
                //1e-5： 误识率为十万分之一的置信度阈值；
                //如果置信值低于“ 千分之一” 阈值则不建议认为是同一个人； 如果置信值超过“ 十万分之一” 阈值， 则是同一个人的几率非常高。
                //如果置信度大于十万分之一的阈值
                if (res1.data.confidence > 70.0) {
                  console.log("11")
                  clearInterval(interval);
                  var now = utils.formatTime(new Date())
                  console.log(`now:${now}`)
                  console.log("" + options.course + "::" + options.courseTime)
                  that.setData({
                    course: options.course,
                    time: options.courseTime
                  })
                  //若未在签到时间内，返回false
                  wx.request({
                    method: 'POST',
                    url: `https://geek-team.xin/signIn/set?student=${app.globalData.sId}&course=${options.course}&courseTime=${options.courseTime}&signinTime=${now}`,
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    success(e) {
                      console.log("12")
                      console.log(e);
                      if (e.data) {
                        // wx.showModal({
                        //   title: '签到成功',
                        //   content: `签到成功`,
                        //   confirmText: "确定",
                        //   success: function (res) {
                        //     console.log(res);
                        //     clearInterval(interval);
                        //     app.globalData.socket.emit("studentSign",
                        //       `{"student":"${app.globalData.sId}","courseTime":"${options.courseTime}","course":"${options.course}","signinTime":"${now}"}`,
                        //       (d) => console.log(d))
                        //     wx.navigateBack()
                        //   },
                        //   fail() {
                        //     wx.navigateBack()
                        //   }
                        // });
                        setTimeout(function () {
                          console.log("sleep")
                        }, 7000)

                        app.globalData.socket.emit("studentSign",
                          `{"student":"${app.globalData.sId}","courseTime":"${options.courseTime}","course":"${options.course}","signinTime":"${now}"}`,
                          (d) => console.log(d))

                        wx.redirectTo({
                          url: "../end/end?state=1&course=" + that.data.course + "&cTime=" + that.data.time
                        })
                      } else {
                        // wx.showToast({
                        //   title: '超出签到时间段',
                        //   image: '../../images/error.png',
                        //   duration: 2000
                        // })
                        wx.redirectTo({
                          url: "../end/end?state=2&course=" + that.data.course + "&cTime=" + that.data.time
                        })
                      }
                    }
                  })
                }
              }
            },
            fail(e) {
              console.log(e);
            }
          })
        }
      })
      .catch(error => console.error(error))
  }
}

// 获得当前时间的课程
function getTodayCourse(that, sid) {
  console.log(that)
  wx.request({
    url: `https://geek-team.xin/schedule/wx_getScheduleNowNow`,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: {
      sId: sid
    },
    success(res) {
      if (res.data != []) {
        that.setData({
          currentcourse: res.data
        })
        console.log("这是最新" + res.data)
      }
    },
    fail: (e) => console.log(e)
  })
}